//
//  AppDelegate.m
//  WeiMo
//
//  Created by weixian he on 12-8-18.
//  Copyright (c) 2012年. All rights reserved.
//

#import "AppDelegate.h"
#import "SDImageCache.h"
#import "SecondViewController.h"
#import "MsgViewCtrl.h"

#import "LoginViewController.h"
#import "SVProgressHUD.h"
#import "InboxAndPersonalViewController.h"

#import "FMManager.h"
#import "JSONKit.h"
#import "KeyValueObject.h"
#import "InterfaceDefine.h"
#import "DLog.h"
#import <libkern/OSMemoryNotification.h>

#define kSlideViewWidth (256.0)

@interface AppDelegate ()
@property (nonatomic,retain) UIView *leftSlideView;

@property (nonatomic,retain) SideBarTableViewController *slideBarController;        //侧边栏

@property (nonatomic,retain) ThreeViewController *threeViewCtrl;                    //首页
@property (nonatomic,retain) MsgViewCtrl *msgViewCtrl;                              //公告页
@property (nonatomic,retain) SecondViewController *secondViewController;            //个人资料
@property (nonatomic,retain) InboxAndPersonalViewController *inboxController;       //收件箱

@property (nonatomic,retain) NSString *updateNumbers;
@end

@implementation AppDelegate
@synthesize leftSlideView;
@synthesize window = _window;
@synthesize tabBarController = _tabBarController;
@synthesize slideBarController,inboxController,threeViewCtrl,msgViewCtrl,secondViewController;
@synthesize updateNumbers;

//ASIFormDataRequest  文件上传

- (void)dealloc
{
    [_window release];
    [_tabBarController release];
    self.leftSlideView = nil;
    self.slideBarController = nil;
    self.threeViewCtrl = nil;
    self.updateNumbers = nil;
    self.inboxController = nil;
    self.msgViewCtrl = nil;
    self.secondViewController = nil;
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.updateNumbers = @"0";
    [[FMManager sharedInstance] initData];
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
  
    UIImage *navImage = [UIImage imageNamed:@"top.png"];
    
    self.threeViewCtrl = [[[ThreeViewController alloc] init] autorelease];
    self.threeViewCtrl.delegate = self;
    UINavigationController *threeNavCtrl = [[UINavigationController alloc] initWithRootViewController:self.threeViewCtrl];
    if ([threeNavCtrl.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [threeNavCtrl.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        UIImageView *threeImageView = [[UIImageView alloc] initWithFrame:threeNavCtrl.navigationBar.frame];
        threeImageView.contentMode = UIViewContentModeLeft;
        threeImageView.image = navImage;
        [threeNavCtrl.navigationBar insertSubview:threeImageView atIndex:0];
        [threeImageView release];
    }
    
    
    //消息公告
    self.msgViewCtrl = [[[MsgViewCtrl alloc] init] autorelease];
    UINavigationController *msgNavCtrl = [[UINavigationController alloc] initWithRootViewController:self.msgViewCtrl];
    if ([msgNavCtrl.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [msgNavCtrl.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        UIImageView *msgImageView = [[UIImageView alloc] initWithFrame:msgNavCtrl.navigationBar.frame];
        msgImageView.contentMode = UIViewContentModeLeft;
        msgImageView.image = navImage;
        [msgNavCtrl.navigationBar insertSubview:msgImageView atIndex:0];
        [msgImageView release];
    }
    
    //收件箱
    self.inboxController = [[[InboxAndPersonalViewController alloc] init] autorelease];
    UINavigationController *navInboxCtrl = [[UINavigationController alloc] initWithRootViewController:self.inboxController];
    
    if ([navInboxCtrl.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [navInboxCtrl.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        UIImageView *inboxImageView = [[UIImageView alloc] initWithFrame:navInboxCtrl.navigationBar.frame];
        inboxImageView.contentMode = UIViewContentModeLeft;
        inboxImageView.image = navImage;
        [navInboxCtrl.navigationBar insertSubview:inboxImageView atIndex:0];
        [inboxImageView release];
    }
    
    
    //请求数据
    [self requestPersonalListDatas];
    //开启定时
    [self setTimeToRefreshAllDatas];
    
    
    self.secondViewController = [[[SecondViewController alloc] init] autorelease];
    self.secondViewController.editType = @"isMy";
    UINavigationController *secondNavCtrl = [[UINavigationController alloc] initWithRootViewController:self.secondViewController];
    if ([secondNavCtrl.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [secondNavCtrl.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        UIImageView *secondImageView = [[UIImageView alloc] initWithFrame:secondNavCtrl.navigationBar.frame];
        secondImageView.contentMode = UIViewContentModeLeft;
        secondImageView.image = navImage;
        [secondNavCtrl.navigationBar insertSubview:secondImageView atIndex:0];
        [secondImageView release];
    }
    
    self.tabBarController = [[[UITabBarController alloc] init] autorelease];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:threeNavCtrl, msgNavCtrl,navInboxCtrl,secondNavCtrl,nil];
    self.tabBarController.delegate = self;
    
    float width = self.window.frame.size.width;
    float height = self.window.frame.size.height;
    CGPoint point = self.window.center;
    CGRect rect = CGRectMake(0, 0, width + kSlideViewWidth, height);
    self.leftSlideView = [[[UIView alloc] initWithFrame:rect] autorelease];
    self.leftSlideView.backgroundColor = [UIColor blackColor];
    
    rect = CGRectMake(kSlideViewWidth, 0, width, height);
    self.tabBarController.view.frame = rect;
    [self.leftSlideView addSubview:self.tabBarController.view];
    [self.leftSlideView setCenter:CGPointMake(point.x - kSlideViewWidth / 2, point.y)];
    [self.window addSubview:self.leftSlideView];
    
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    
    [threeNavCtrl release];
    [msgNavCtrl release];
    [navInboxCtrl release];
    [secondNavCtrl release];
    
    return YES;
}

-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    DEnter();
    [[SDImageCache sharedImageCache] clearMemory];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
}
*/

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
}
*/

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if(self.secondViewController && [viewController.title isEqualToString:@"我的资料"])
    {
        self.secondViewController.editType = @"isMy";
        [self.secondViewController myRefeash];
    }
    
    /*
    FMManager *manager = [FMManager sharedInstance];
    if([viewController.title isEqualToString:@"Four"] && manager.isLogin == NO)
    {
        mTableBarIndex = 3;
        //[SVProgressHUD show];
        LoginViewController *loginCtrl = [[LoginViewController alloc] init];
        loginCtrl.delegate = self;
        [loginCtrl initWithStyle:UITableViewStyleGrouped];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginCtrl];
        [loginCtrl release];
        nav.navigationBar.barStyle = UIBarStyleBlack;
        UINavigationController *navTemp=(UINavigationController *)[tabBarController.viewControllers objectAtIndex:0];
        [navTemp presentModalViewController:nav animated:YES];
        [nav release];
        return NO;
    }
    else if([viewController.title isEqualToString:@"我的资料"] && manager.isLogin == NO)
    {
        //[SVProgressHUD show];
        mTableBarIndex = 2;
        LoginViewController *loginCtrl = [[LoginViewController alloc] init];
        loginCtrl.delegate = self;
        [loginCtrl initWithStyle:UITableViewStyleGrouped];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginCtrl];
        [loginCtrl release];
        nav.navigationBar.barStyle = UIBarStyleBlack;
        UINavigationController *navTemp=(UINavigationController *)[tabBarController.viewControllers objectAtIndex:0];
        [navTemp presentModalViewController:nav animated:YES];
        [nav release];
        return NO;
    }
     */
    
    return YES;
}

#pragma mark - private methods

//定时刷新
- (void)setTimeToRefreshAllDatas
{
    [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(requestPersonalListDatas) userInfo:nil repeats:YES];
}

//请求资料收件箱数据
- (void)requestInboxDatas
{
    NSString *userId = [[FMManager sharedInstance] userId];
    if (!userId || userId.length <= 0)
    {
        return;
    }
}

//请求私信列表数据
- (void)requestPersonalListDatas
{
    NSString *userId = [[FMManager sharedInstance] userId];
    if (!userId || userId.length <= 0)
    {
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",kHttpHost,kQueryPFuserList];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:@"1" forKey:@"startPage"];
    [dic setValue:@"10000" forKey:@"pageSize"];
    [dic setValue:userId forKey:@"toUserid"];
    NSString *post = [dic JSONString];
    [dic release];
    
    DLog(@"url:%@,post:%@",url,post);
    
    ASIHTTPRequest *appDelegateRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [appDelegateRequest setDelegate:self];
    [appDelegateRequest appendPostData:[post dataUsingEncoding:NSUTF8StringEncoding]];
    [appDelegateRequest setRequestMethod:@"POST"];
    [appDelegateRequest startAsynchronous];
}

//统计并显示更新数据条数
//flag:1--收件箱  2--私信
- (void)staticPersonalDatas:(NSArray *)array flag:(int)flag
{
    int count1 = 0;
    int count2 = 0;
    if (flag == 1)
    {
        
    }
    else
    {
        for (int i=0; i<array.count; i++)
        {
            NSDictionary *dic = [array objectAtIndex:i];
            NSString *number = [dic objectForKey:@"unreadPage"];
            count2 = count2 + number.intValue;
        }
        
        [self.inboxController refreshPersonalInboxNumbers:count2 withFlag:2];
    }
    
    self.updateNumbers = [NSString stringWithFormat:@"%d",(count1 + count2)];
    UITabBarItem *tabItem =  [[[self.tabBarController tabBar] items] objectAtIndex:2];
    if (self.updateNumbers.intValue > 0)
    {
        tabItem.badgeValue = self.updateNumbers;
    }
    else
    {
        tabItem.badgeValue = nil;
    }
}

#pragma mark - LoginViewControllerDelegate
-(void)loginOK
{
    self.tabBarController.selectedIndex = mTableBarIndex;
}

#pragma mark - ThreeViewControllerDelegate

- (void)showSlideBarViwButtonClicked:(BOOL)flag
{
    CGPoint point = self.window.center;
    float pX = 0.0;
    if (flag)
    {
        pX = (kSlideViewWidth + 320) / 2;
        
        if (self.slideBarController == nil)
        {
            CGRect rect = CGRectMake(0, 20, kSlideViewWidth, self.window.frame.size.height-20);
            self.slideBarController = [[[SideBarTableViewController alloc] init] autorelease];
            self.slideBarController.view.frame = rect;
            self.slideBarController.delegate = self;
            [self.leftSlideView addSubview:self.slideBarController.view];
        }
        
        self.threeViewCtrl.slideBarDisappearButton.hidden = NO;
    }
    else
    {
        pX = point.x - kSlideViewWidth / 2;
        self.threeViewCtrl.slideBarDisappearButton.hidden = YES;
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [self.leftSlideView setCenter:CGPointMake(pX, point.y)];
    [UIView commitAnimations];
}

#pragma mark - SideBarTableViewControllerDelegate

- (void)clickedSlideBarOneItem:(KeyValueObject *)itemValues
{
    [self.threeViewCtrl releaseTableViewDatas];
    KeyValueObject *item = [[KeyValueObject alloc] init];
    item.key = itemValues.key;
    item.keyDispName = itemValues.keyDispName;
    item.value = @"0";
    [self.threeViewCtrl refreshTitleAndDatas:item];
    [item release];
    
    [self showSlideBarViwButtonClicked:NO];
    [[FMManager sharedInstance] setSlideBarHideFlagWithBoolValue:YES];
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFailed:(ASIHTTPRequest *)request
{
    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSString *urlStr = [NSString stringWithFormat:@"%@",request.url];
    NSRange range = [urlStr rangeOfString:@"/"];
    if (range.location != NSNotFound)
    {
        NSArray *array = [urlStr componentsSeparatedByString:@"/"];
        urlStr = [array objectAtIndex:(array.count - 1)];
    }
    
    NSData *data = [request responseData];
    if ([urlStr isEqualToString:kQueryPFuserList])
    {
        NSArray *result = [data objectFromJSONData];
        if (result.count > 0)
        {
            NSString *status = [result objectAtIndex:0];
            if ([status isEqualToString:kResponseOk])
            {
                NSDictionary *dic = [result objectAtIndex:1];
                NSArray *array = [dic objectForKey:@"data"];
                [[FMManager sharedInstance] refreshPersonalFriendListDatas:array];
                [self staticPersonalDatas:array flag:2];
            }
        }
    }
}

@end